package io.renren.modules.aic.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.aic.entity.BalanceTopupEntity;
import io.renren.modules.aic.entity.CtocOrderEntity;
import io.renren.modules.aic.entity.MachineGiveEntity;
import io.renren.modules.aic.entity.MemberEntity;
import io.renren.modules.aic.service.BalanceTopupService;
import io.renren.modules.aic.service.CtocOrderService;
import io.renren.modules.aic.service.MachineGiveService;
import io.renren.modules.aic.service.MemberService;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 会员表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-03-28 12:39:07
 */
@RestController
@RequestMapping("aic/member")
public class MemberController {
	@Autowired
	private MemberService memberService;

	@Autowired
	private CtocOrderService ctocOrderService;

	@Autowired
	private MachineGiveService machineGiveService;

	@Autowired
	private BalanceTopupService balanceTopupService;

	/**
	 * 列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	@RequiresPermissions("aic:member:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = memberService.queryPage(params);
		List<MemberEntity> list = (List<MemberEntity>) page.getList();
		if (CollectionUtils.isNotEmpty(list)) {
			for (MemberEntity memberEntity : list) {
				if (StringUtils.isNotBlank(memberEntity.getRecPerson())) {
					MemberEntity entity = memberService.selectOne(new EntityWrapper<MemberEntity>().eq("code", memberEntity.getRecPerson()));
					memberEntity.setRecPerson(entity.getMobile() + (StringUtils.isNotBlank(entity.getRealname()) ? "(" + entity.getRealname() + ")" : ""));
				}
			}
		}
		return R.ok().put("page", page);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("aic:member:info")
	public R info(@PathVariable("id") Long id) {
		MemberEntity member = memberService.selectById(id);
		return R.ok().put("member", member);
	}

	/**
	 * 保存
	 */
	@SysLog("添加会员")
	@RequestMapping("/save")
	@RequiresPermissions("aic:member:save")
	public R save(@RequestBody MemberEntity member) {
		// 校验类型
		ValidatorUtils.validateEntity(member, AddGroup.class);
		member.setMobile(StringUtils.deleteWhitespace(member.getMobile()));
		memberService.save(member);
		return R.ok();
	}

	/**
	 * 修改
	 */
	@SysLog("修改会员信息")
	@RequestMapping("/update")
	@RequiresPermissions("aic:member:update")
	public R update(@RequestBody MemberEntity member) {
		// 校验类型
		ValidatorUtils.validateEntity(member, UpdateGroup.class);
		member.setMobile(StringUtils.deleteWhitespace(member.getMobile()));
		MemberEntity m = memberService.selectById(member.getId());
		Assert.notNull(m, "更新失败");
		String newMobile = member.getMobile();
		String oldMobile = m.getMobile();
		member.setRecPerson(null);
		member.setCode(null);
		// sha256加密
		if (StringUtils.isNotBlank(member.getPassword())) {
			member.setPassword(DigestUtils.sha256Hex(member.getPassword() + m.getSalt()));
		}
		if (StringUtils.isNotBlank(member.getPayword())) {
			member.setPayword(DigestUtils.sha256Hex(member.getPayword() + m.getSalt()));
		}
		Date now = new Date();
		member.setUpdateTime(now);
		memberService.updateById(member);

		if (!newMobile.equals(oldMobile)) {
			// 更新挂单中的手机
			CtocOrderEntity ctocOrder = new CtocOrderEntity();
			ctocOrder.setMobile(newMobile);
			ctocOrder.setUpdateTime(now);
			ctocOrderService.update(ctocOrder, new EntityWrapper<CtocOrderEntity>().eq("member_id", member.getId()));

			// 更新发放矿机的手机
			MachineGiveEntity machine = new MachineGiveEntity();
			machine.setMobile(newMobile);
			machineGiveService.update(machine, new EntityWrapper<MachineGiveEntity>().eq("member_id", member.getId()));

			// 更新充值表中的手机
			BalanceTopupEntity balanceTopup = new BalanceTopupEntity();
			balanceTopup.setMobile(newMobile);
			balanceTopupService.update(balanceTopup, new EntityWrapper<BalanceTopupEntity>().eq("member_id", member.getId()));
		}

		// 修改了认证状态[认证通过]后赠送迷你矿机
		if (member.getAuthStatus() != null && member.getAuthStatus() == ProjectConstant.AUTH_STATUS_PASSED && m.getAuthStatus() != ProjectConstant.AUTH_STATUS_PASSED) {
			memberService.changeStauts("RZTG", Arrays.asList(member.getId()));
		}

		return R.ok();
	}

	/**
	 * 认证封号
	 */
	@SysLog("认证封号")
	@RequestMapping(path = "/changeStauts", method = RequestMethod.POST)
	@RequiresPermissions("aic:member:update")
	public R changeStauts(String type, Long[] memberIds) {
		Assert.hasText(type, "参数异常[type]");
		Assert.notNull(memberIds, "memberIds is null");
		Assert.noNullElements(memberIds, "参数异常[memberIds]");
		memberService.changeStauts(type, Arrays.asList(memberIds));
		return R.ok();
	}
}
